import RPi.GPIO as GPIO
import time
import serial

led = 2
ser = None

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(led, GPIO.OUT)


def led_on():
    GPIO.output(led, GPIO.HIGH)


def led_off():
    GPIO.output(led, GPIO.LOW)


def led_blink():
    led_on()
    time.sleep(0.1)
    led_off()
    time.sleep(0.1)
    led_on()
    time.sleep(0.1)
    led_off()
    time.sleep(0.1)


def ser_open():
    global ser
    ser = serial.Serial('/dev/ttyAMA0', 115200)
    if not ser.isOpen:
        ser.open()
    ser.write(b"ready!")


def ser_write(msg):
    global ser
    ser.write(bytes(msg, encoding='utf8'))


def ser_read():
    size = ser.inWaiting()  # 获得缓冲区字符
    if size != 0:
        response = ser.read(size)  # 读取内容并显示
        ser.flushInput()  # 清空接收缓存区
        return response
    else:
        return False
